﻿using IM.Easy.Api.Options.OAuth;
using IM.Easy.Core.AppContext;
using IM.Easy.Core.Options;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OAuth;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text.Json;
//using AspNet.Security.OAuth

namespace IM.Easy.Api.OAuth
{
    /// <summary>
    /// 第三方授权 open auth
    /// </summary>
    public static class SocialAuthentication
    {
        public static AuthenticationBuilder AddGiteeAuthentication(this AuthenticationBuilder builder)
        {
            var giteeOptions = ImApp.Configuration.Get<GiteeAuthOptions>();


            //builder.AddGitee(options =>
            //{
            //    options.ClientId = giteeOptions.ClientId;
            //    options.ClientSecret = giteeOptions.ClientSecret;
            //    //options.CallbackPath = giteeOptions.CallbackPath ?? "/signin-gitee";
            //    //options.Scope.Add("user_info");
            //    //options.SaveTokens = true;

            //    //options.Events = new OAuthEvents
            //    //{
            //    //    OnCreatingTicket = async context =>
            //    //    {
            //    //        var request = new HttpRequestMessage(HttpMethod.Get, "https://gitee.com/api/v5/user");
            //    //        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            //    //        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);

            //    //        var response = await context.Backchannel.SendAsync(request, context.HttpContext.RequestAborted);
            //    //        response.EnsureSuccessStatusCode();
            //    //        var user = JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement;

            //    //        context.Identity?.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.GetProperty("id").GetString() ?? ""));
            //    //        context.Identity?.AddClaim(new Claim(ClaimTypes.Name, user.GetProperty("login").GetString() ?? ""));
            //    //    }
            //    //};
            //});

            return builder;
        }
    }
}
